import { updateUserCustomConfigApi } from "@/api/common";
import CommonHook from "@/hook/commonHook";
import { message } from "ant-design-vue";
import { cloneDeep } from "lodash";
import { Ref } from "vue";
import { useRoute } from "vue-router";
import PermissionStore from "@/store/modules/permission";
export default function OperationHook(state: {
  emit: any;
  activeKey: Ref<string>;
  loading: Ref<boolean>;
  fieldTableRef: Ref<any>;
  puppeteer: Ref<Array<SuperTable.TableCoulmnItem | SuperTable.NestTableColumnItem>>;
  allLeftFixedCount: Ref<number>;
  allRightFixedCount: Ref<number>;
}) {
  const { emit, puppeteer, fieldTableRef, activeKey, loading, allLeftFixedCount, allRightFixedCount } = state;
  const route = useRoute();
  const { isArray, stringify, parse } = CommonHook();
  const cancelHandle = () => {
    emit("update:visible", false);
  };
  const submitHandle = () => {
    if (allLeftFixedCount.value > 3) return message.info("最多3列左固定!");
    if (allRightFixedCount.value > 3) return message.info("最多3列右固定!");
    const showFieldList = fieldTableRef.value.getCheckboxRecords().map((t: any) => t.field);
    for (let i = 0; i < puppeteer.value.length; i++) {
      const target = puppeteer.value[i];
      target.isShow = showFieldList.includes(target.field);
    }
    const targetConfig = parse(window.localStorage.getItem("fieldColumn") || "{}");
    if (targetConfig[route.path]) {
      if (activeKey.value) {
        if (isArray(targetConfig[route.path])) return console.warn("配置异常、期望得到对象但是意外的得到数组!");
        else {
          targetConfig[route.path][activeKey.value] = cloneDeep(puppeteer.value);
        }
      } else {
        targetConfig[route.path] = cloneDeep(puppeteer.value);
      }
    } else {
      if (activeKey.value) {
        if (isArray(targetConfig[route.path])) return console.warn("配置异常、期望得到对象但是意外的得到数组!");
        targetConfig[route.path] = {
          [activeKey.value]: cloneDeep(puppeteer.value)
        };
      } else {
        targetConfig[route.path] = cloneDeep(puppeteer.value);
      }
    }
    window.localStorage.setItem("fieldColumn", stringify(targetConfig));
    PermissionStore.fieldColumn = targetConfig;
    loading.value = true;
    updateUserCustomConfigApi(stringify(targetConfig))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("submit", puppeteer.value);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  return {
    cancelHandle,
    submitHandle
  };
}
